class Solution {
public:
    struct apple
    {
        int produce;
        int count;
        int days;
        int duration;

        apple(int p, int c, int d) : produce(p), count(c), days(d){
            duration = produce + days;
        }
    };

    struct Compare
    {
        bool operator()(const apple& a1, const apple& a2)
        {
            int duration1 = a1.produce + a1.days; 
            int duration2 = a2.produce + a2.days; 
            return duration1 > duration2;
        }
    };
    int eatenApples(vector<int>& apples, vector<int>& days) {
        priority_queue<apple, vector<apple>, Compare> appQu;
        int n = apples.size(), ans = 0;
        for(int i = 0; i < n || !appQu.empty(); ++i)
        {
            while(!appQu.empty() && appQu.top().duration == i) appQu.pop();

            if(i < n && apples[i] != 0) 
                appQu.push(apple(i, apples[i], days[i]));

            if(!appQu.empty())
            {
                ++ans;
                auto top = appQu.top();
                int p = top.produce, c = top.count, d = top.days;
                appQu.pop();
                if(c > 1)
                    appQu.push(apple(p, c - 1, d));
            }
        }
        return ans;
    }
};
